package com.zhang.third.day03;

import com.zhang.third.utils.Event;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.connector.jdbc.JdbcStatementBuilder;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @title: 使用flink提供的JDBC连接mysql
 * @author: zhang
 * @date: 2022/4/6 10:14
 */
public class Example4 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        env
                .fromElements(
                        new Event("Mary", "./home", 1000L),
                        new Event("Bob", "./cart", 2000L),
                        new Event("Alice", "./prod?id=100", 3000L),
                        new Event("Alice", "./prod?id=200", 3500L),
                        new Event("Bob", "./prod?id=2", 2500L),
                        new Event("Alice", "./prod?id=300", 3600L),
                        new Event("Bob", "./home", 3000L),
                        new Event("Bob", "./prod?id=1", 2300L),
                        new Event("Bob", "./prod?id=3", 3300L)
                )
                .addSink(JdbcSink.sink(
                        "INSERT INTO clicks1 (name,url) VALUES (?,?)",
                        new JdbcStatementBuilder<Event>() {
                            @Override
                            public void accept(PreparedStatement preparedStatement, Event event) throws SQLException {
                                preparedStatement.setString(1, event.key);
                                preparedStatement.setString(2, event.value);
                            }
                        },
                        new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                                .withUrl("jdbc:mysql://localhost:3306/userbehavior?useSSl=false")
                                .withDriverName("com.mysql.jdbc.Driver")
                                .withUsername("root")
                                .withPassword("000000")
                                .build()

                ));

        env.execute();
    }
}
